//
//  ViewController.swift
//  quickWeather
//
//  Created by Symbol on 14/11/25.
//  Copyright (c) 2014年 Symbol. All rights reserved.
//

import UIKit
import CoreLocation

class ViewController: UIViewController,CLLocationManagerDelegate {
    
    @IBOutlet weak var today: UITextView!
    
    let locationManager : CLLocationManager = CLLocationManager()//定位实例化

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        //设置代理绑定
        locationManager.delegate = self
        
        //方法初始化
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()
        
        //启动
        locationManager.startUpdatingLocation()
        
        
    }

    
    //实现获得地理信息方法
    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!){
        
        var location = locations[locations.count - 1] as CLLocation
        
        if location.coordinate.latitude > 0{
            
            locationManager.stopUpdatingLocation()
        }
        
        var test : String
        //begin
        var geocoder = CLGeocoder()
        var p:CLPlacemark?
        geocoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
            if error != nil {
                println("reverse geodcode fail: \(error.localizedDescription)")
                return
            }
            let pm = placemarks as [CLPlacemark]
            if (pm.count > 0){
                p = placemarks[0] as? CLPlacemark
                self.newinfo(p!)
                println("当前地址是：\(p!.locality)")
            }else{
                println("没有查询到地址!")
            }
        })
        //end
    }
    
    func newinfo(p : CLPlacemark){
        var cityName = p.locality//获得城市名称
        
        var elInfo : baiscInfo
        
        if (cityName != nil){
            if (cityName != "沙市" && cityName != "呼市郊区" && cityName != "津市" && cityName != "芒市"){
                cityName = cityName!.stringByReplacingOccurrencesOfString("市", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
            }
            
            elInfo = getIntWeather(cityName!)
            var todayInfo = "今日\(elInfo.week),气温:\(elInfo.temperature1),风速:\(elInfo.windSpeed1),风向:\(elInfo.air),紫外线状况:\(elInfo.ultraviolet),锻炼建议:\(elInfo.duanlian),洗车建议:\(elInfo.xcar),旅游建议:\(elInfo.traveling),晾晒建议:\(elInfo.air)"
            println(todayInfo)
            today.text = todayInfo
        }
    }
    
    
    //实现调用错误的方法
    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!){
        locationManager.stopUpdatingLocation()//结束定位
        println("定位失败，结束程序\(error)")
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

